from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import List, Optional
import os
import yaml

router = APIRouter(prefix="/api/llm", tags=["LLM Configuration Management"])

# 配置文件目录
CONFIG_DIR = os.path.join(os.path.dirname(__file__), "llm_config")

# 确保配置目录存在
os.makedirs(CONFIG_DIR, exist_ok=True)

class LLMConfigBase(BaseModel):
    """LLM配置基础模型"""
    config: dict

class LLMCreateRequest(BaseModel):
    """创建LLM配置请求模型
    Attributes:
        yaml_name: 配置文件名
        config: LLM配置字典
    """
    yaml_name: str
    config: dict

class LLMDeleteRequest(BaseModel):
    """删除LLM配置请求模型
    Attributes:
        yaml_name: 要删除的配置文件名
    """
    yaml_name: str

class LLMUpdateRequest(BaseModel):
    """更新LLM配置请求模型
    Attributes:
        yaml_name: 要更新的配置文件名
        config: 新的LLM配置
    """
    yaml_name: str
    config: dict

@router.get("/list")
async def list_llm_configs():
    """获取所有LLM配置文件列表
    - 返回结构:包含所有yaml文件名的列表
    """
    try:
        # 获取llm_config目录下所有yaml文件
        yaml_files = [f for f in os.listdir(CONFIG_DIR) if f.endswith(".yaml") or f.endswith(".yml")]
        return {"code": 200, "message": "success", "data": yaml_files}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/get/{yaml_name}")
async def get_llm_config(yaml_name: str):
    """获取指定LLM配置文件内容
    - 参数校验:yaml_name必须存在
    """
    try:
        # 确保文件名有.yaml后缀
        if not yaml_name.endswith(".yaml") and not yaml_name.endswith(".yml"):
            yaml_name = f"{yaml_name}.yaml"
            
        file_path = os.path.join(CONFIG_DIR, yaml_name)
        
        # 检查文件是否存在
        if not os.path.exists(file_path):
            raise HTTPException(status_code=404, detail=f"配置文件 {yaml_name} 不存在")
        
        # 读取yaml文件内容
        with open(file_path, 'r', encoding='utf-8') as f:
            config = yaml.safe_load(f)
        
        return {"code": 200, "message": "success", "data": config}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/create")
async def create_llm_config(request: LLMCreateRequest):
    """创建新的LLM配置
    - 参数校验:自动通过Pydantic模型校验
    - 配置保存:将配置以yaml格式保存到llm_config目录
    """
    try:
        # 确保文件名有.yaml后缀
        yaml_name = request.yaml_name
        if not yaml_name.endswith(".yaml") and not yaml_name.endswith(".yml"):
            yaml_name = f"{yaml_name}.yaml"
            
        file_path = os.path.join(CONFIG_DIR, yaml_name)
        
        # 检查文件是否已存在
        if os.path.exists(file_path):
            raise HTTPException(status_code=400, detail=f"配置文件 {yaml_name} 已存在")
        
        # 将配置写入yaml文件
        with open(file_path, 'w', encoding='utf-8') as f:
            yaml.dump(request.config, f, default_flow_style=False, allow_unicode=True)
        
        return {"code": 200, "message": "success"}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/delete")
async def delete_llm_config(request: LLMDeleteRequest):
    """删除指定LLM配置文件
    - 参数校验:yaml_name必须存在
    """
    try:
        # 确保文件名有.yaml后缀
        yaml_name = request.yaml_name
        if not yaml_name.endswith(".yaml") and not yaml_name.endswith(".yml"):
            yaml_name = f"{yaml_name}.yaml"
            
        file_path = os.path.join(CONFIG_DIR, yaml_name)
        
        # 检查文件是否存在
        if not os.path.exists(file_path):
            raise HTTPException(status_code=404, detail=f"配置文件 {yaml_name} 不存在")
        
        # 删除文件
        os.remove(file_path)
        
        return {"code": 200, "message": "success"}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/update")
async def update_llm_config(request: LLMUpdateRequest):
    """更新指定LLM配置
    - 参数校验:yaml_name必须存在
    - 配置更新:更新对应yaml文件内容
    """
    try:
        # 确保文件名有.yaml后缀
        yaml_name = request.yaml_name
        if not yaml_name.endswith(".yaml") and not yaml_name.endswith(".yml"):
            yaml_name = f"{yaml_name}.yaml"
            
        file_path = os.path.join(CONFIG_DIR, yaml_name)
        
        # 检查文件是否存在
        if not os.path.exists(file_path):
            raise HTTPException(status_code=404, detail=f"配置文件 {yaml_name} 不存在")
        
        # 将配置写入yaml文件
        with open(file_path, 'w', encoding='utf-8') as f:
            yaml.dump(request.config, f, default_flow_style=False, allow_unicode=True)
        
        return {"code": 200, "message": "success"}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))